package com.dongan.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongan.pojo.DesignProcedure;
import com.dongan.pojo.DesignProcedureDetails;
import com.dongan.pojo.File;
import com.dongan.pojo.Users;
import com.dongan.service.CodesService;
import com.dongan.service.DesignProcedureDetailsService;
import com.dongan.service.DesignProcedureService;
import com.dongan.service.FileService;
import com.dongan.utils.GetSysDateTime;
import com.dongan.utils.NumberFormatUtil;
import com.dongan.utils.ResultResponseUtil;
import com.dongan.utils.SerialNumber;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生产工序设计
 *
 * @author longTao
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/design-procedure")
@CrossOrigin
public class DesignProcedureController {
    @Autowired
    private DesignProcedureService service;
    @Autowired
    private DesignProcedureDetailsService detailsService;
    @Autowired
    private FileService fileService;
    @Autowired
    private CodesService codesService;

    /**
     * 查询模块
     * @param pageSize
     * @param checkTag
     * @param firstId
     * @param secondId
     * @param threeId
     * @param pageNum
     * @return
     */
    @GetMapping("/queryProcedure")
    @PreAuthorize("hasAuthority('/productProductionProcessDesignSheetReview')")
    public Object queryProcedure(String designModuleTag,String productName,String pageSize, String checkTag, String firstId, String secondId, String threeId, String pageNum) {
        QueryWrapper<DesignProcedure> queryWrapper = new QueryWrapper<>();
        Page<DesignProcedure> filePage = new Page<>();
        if (!StringUtils.isEmpty(firstId)) {
            queryWrapper.eq("FIRST_KIND_ID", Long.valueOf(firstId));
        }
        if (!StringUtils.isEmpty(checkTag)) {
            queryWrapper.eq("CHECK_TAG", checkTag);
        }
        if (!StringUtils.isEmpty(secondId)) {
            queryWrapper.eq("SECOND_KIND_ID", Long.valueOf(secondId));
        }
        if (!StringUtils.isEmpty(threeId)) {
            queryWrapper.eq("THIRD_KIND_ID", Long.valueOf(threeId));
        }
        if (!StringUtils.isEmpty(firstId)) {
            queryWrapper.eq("PRODUCT_NAME", productName);
        }
        if (!StringUtils.isEmpty(designModuleTag)) {
            queryWrapper.eq("DESIGN_MODULE_TAG", designModuleTag);
        }
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "2";
        }
        filePage.setSize(Long.valueOf(pageSize));
        filePage.setCurrent(Long.valueOf(pageNum));
        Page<DesignProcedure> page = service.page(filePage, queryWrapper);
        System.out.println("page = " + page);
        return new ResultResponseUtil(true,page);
    }
    /**
     * 添加工序设计
     * @param map
     * @return
     */
    @PostMapping("/addProcedure")
    @PreAuthorize("hasAuthority('/developProductProductionProcessDesignSheet')")
    public Object addDP(@RequestBody Map<String,Object> map){
        DesignProcedure procedure=null;
        List<DesignProcedureDetails> details=null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            procedure=mapper.readValue(mapper.writeValueAsString(map.get("procedure")),DesignProcedure.class);
            details=mapper.readValue(mapper.writeValueAsString(map.get("details")), new TypeReference<List<DesignProcedureDetails>>() {
            });
            System.out.println("procedure = " + procedure);
            for (DesignProcedureDetails detail : details) {
                System.out.println("detail = " + detail);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        boolean flag=service.insertProcedure(procedure,details);
        String msg="添加失败!";
        if(flag){
            msg="添加成功!";
        }
        return new ResultResponseUtil(flag,msg);
    }

    /**
     * 审核
     * @param procedure
     * @return
     */
    @PostMapping("/checkProcedure")
    @PreAuthorize("hasAuthority('/productProductionProcessDesignSheetReview')")
    public Object checkModule(@RequestBody DesignProcedure procedure) {
        //CHECKER	复核人
        Users users= (Users) SerialNumber.user;
        procedure.setChecker(users.getLoginId());
        //CHECK_TIME	审核时间
        procedure.setCheckTime(GetSysDateTime.getDatetime());
        boolean flag = service.updateById(procedure);
        if (!"S001-1".equals(procedure.getCheckTag())) {
            File file = new File();
            file.setDesignProcedureTag("G001-0");
            UpdateWrapper<File> wrapper=new UpdateWrapper<>();
            wrapper.eq("PRODUCT_ID",procedure.getProductId());
            boolean flag2=fileService.updateById(file);

            UpdateWrapper<DesignProcedureDetails> wrapper2=new UpdateWrapper<>();
            wrapper.eq("PARENT_ID",procedure.getId());
            boolean flag3=detailsService.remove(wrapper2);
            if(flag2 && flag3){
                return new ResultResponseUtil(true, "已审核!");
            }
        }
        if (flag){
            return new ResultResponseUtil(flag, "审核成功!");
        }else {
            return new ResultResponseUtil(flag,"审核失败!");
        }
    }

    /**
     * 修改工序设计
     * @param map
     * @return
     */
    @PostMapping("/updateProcedure")
    @PreAuthorize("hasAuthority('/productProductionProcessDesignOrderChange')")
    public Object updateProcedure(@RequestBody Map<String,Object> map){
        DesignProcedure procedure=null;
        List<DesignProcedureDetails> details=null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            procedure=mapper.readValue(mapper.writeValueAsString(map.get("procedure")),DesignProcedure.class);
            details=mapper.readValue(mapper.writeValueAsString(map.get("details")), new TypeReference<List<DesignProcedureDetails>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        boolean flag=service.updateProcedure(procedure,details);
        String msg="修改失败!";
        if(flag){
            msg="修改成功!";
        }
        return new ResultResponseUtil(flag,msg);
    }
    /**
     * 修改工序设计
     * @param id
     * @return
     */
    @GetMapping("/queryById")
    @PreAuthorize("hasAuthority('/productProductionProcessDesignSheetReview')")
    public Object queryById(Long id){
        QueryWrapper<DesignProcedure> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("PRODUCT_ID",id);
        DesignProcedure procedure =service.getOne(queryWrapper);
        if (procedure==null){
            return new ResultResponseUtil("你母亲死了");
        }
        QueryWrapper<DesignProcedureDetails> detailsQueryWrapper=new QueryWrapper<>();
        detailsQueryWrapper.eq("PARENT_ID",procedure.getId());
        List<DesignProcedureDetails> list = detailsService.list(detailsQueryWrapper);
        Map<String,Object> map=new HashMap<>();
        map.put("procedure",procedure);
        map.put("list",list);
        return new ResultResponseUtil(true, "查询成功!", map);
    }
    /**
     *变更/提交工序物料设计
     * @param id
     * @return
     */
    @GetMapping("/commitProcedure")
    @PreAuthorize("hasAnyAuthority('/developProcessMaterialDesignSheet','/developProductProductionProcessDesignSheet')")
    public Object commitProcedure(Long id){
        //工序物料设计标志
        //审核 DESIGN_MODULE_TAG
        DesignProcedure procedure=new DesignProcedure();
        procedure.setId(id);
        procedure.setDesignModuleTag("G002-1");
        boolean flag=service.updateById(procedure);
        String message="";
        if (flag){
            message="添加成功!";
        }else {
            message="添加失败!";
        }
        return new ResultResponseUtil(flag,message);
    }
}

